package com.jdd.modules.parking.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.jdd.common.api.vo.Result;
import com.jdd.common.aspect.annotation.*;
import com.jdd.common.system.query.QueryGenerator;
import com.jdd.common.util.excel.entity.params.ExportParams;
import com.jdd.common.util.excel.entity.params.ImportParams;
import com.jdd.common.util.excel.util.ExcelImportUtil;
import com.jdd.common.util.excel.web.entity.vo.NormalExcelConstants;
import com.jdd.common.util.excel.web.view.EasypoiSingleExcelView;
import com.jdd.modules.parking.entity.ZombieCar;
import com.jdd.modules.parking.service.IZombieCarService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * @author jdd
 */
@Slf4j
@Api(tags = "场内滞留车信息")
@RestController
@RequestMapping("/parking/zombieCar")
public class ZombieCarController {
    @Resource
    private IZombieCarService zombieCarService;

    @AutoLog(value = "场内滞留车信息-统计滞留车数量")
    @ApiOperation(value = "场内滞留车信息-统计滞留车数量", notes = "场内滞留车信息-统计滞留车数量")
    @GetMapping(value = "/zombieNumer")
    public Result<Integer> getZombieNumer() {
        Result<Integer> result = new Result<Integer>();
        try {
            Integer zombieNumer = zombieCarService.getZombieNumer();
            result.setResult(zombieNumer);
            result.success("查询成功！");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            result.error500("查询异常");
        }
        return result;
    }

    /**
     * 分页列表查询
     *
     * @param zombieCar
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "场内滞留车信息-分页列表查询")
    @ApiOperation(value = "场内滞留车信息-分页列表查询", notes = "场内滞留车信息-分页列表查询")
    @GetMapping(value = "/list")
    public Result<IPage<ZombieCar>> queryPageList(ZombieCar zombieCar,
                                                  @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                  @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                  HttpServletRequest req) {
        Result<IPage<ZombieCar>> zombieList = new Result<>();
        try {
            //数据库的结果
            zombieList = zombieCarService.findZombieList(zombieCar, pageNo, pageSize, req);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            zombieList.error500("查询异常！！！");
        }
        return zombieList;
    }

    /**
     * 滞留车出场
     *
     * @param id
     * @return
     */
    @AutoLog(value = "场内滞留车信息-滞留车出场")
    @ApiOperation(value = "场内滞留车信息-滞留车出场", notes = "场内滞留车信息-滞留车出场")
    @GetMapping(value = "/out")
    @OperationLogDetail(detail = "场内滞留车信息，滞留车出场", level = LogLevelType.ONE, operationType = OperationType.DELETE, operationUnit = OperationUnit.UNKNOWN)
    public Result<?> out(@RequestParam(name = "plateNo", required = true) String plateNo,
                         @RequestParam(name = "armId", required = false) String armId) {
        Result<ZombieCar> result = new Result<ZombieCar>();
        try {
            zombieCarService.zombieToOut(plateNo, armId);
            result.success("出场成功！");
        } catch (Exception e) {
            log.error("滞留车出场失败，异常信息:{}", e);
            result.error500("出场失败");
        }
        return result;
    }

    /**
     * 场内滞留车信息 -批量出场
     *
     * @param ids   车辆入场id列表
     * @param armId 车道id
     * @return 返回出场结果
     */
    @AutoLog(value = "场内滞留车信息-批量出场")
    @ApiOperation(value = "场内滞留车信息-批量出场", notes = "场内滞留车信息-批量删除")
    @GetMapping(value = "/outBatch")
    @OperationLogDetail(detail = "场内滞留车信息，批量出场", level = LogLevelType.ONE, operationType = OperationType.DELETE, operationUnit = OperationUnit.UNKNOWN)
    public Result<ZombieCar> outBatch(@RequestParam(name = "plateNos", required = true) String plateNos,
                                      @RequestParam(name = "armId", required = false) String armId) {
        Result<ZombieCar> result = new Result<>();
        if (plateNos == null || "".equals(plateNos.trim())) {
            result.error500("参数不识别！");
            return result;
        }
        try {
            String[] plateNoList = plateNos.split(",");
            for (String plateNo : plateNoList) {
                zombieCarService.zombieToOut(plateNo, armId);
            }
            result.success("出场成功!");
        } catch (Exception e) {
            log.error("滞留车批量出场失败，异常信息:{}", e);
            result.error500("出场失败");
        }
        return result;
    }


    /**
     * 滞留车设置黑名单
     *
     * @param id
     * @return
     */
    @AutoLog(value = "场内滞留车信息-滞留车设置黑名单")
    @ApiOperation(value = "场内滞留车信息-滞留车设置黑名单", notes = "场内滞留车信息-滞留车设置黑名单")
    @GetMapping(value = "/black")
    @OperationLogDetail(detail = "场内滞留车信息，滞留车设置黑名单", level = LogLevelType.ONE, operationType = OperationType.DELETE, operationUnit = OperationUnit.UNKNOWN)
    public Result<?> black(@RequestParam(name = "id", required = true) String id) {
        Result<ZombieCar> result = new Result<ZombieCar>();
        try {
            boolean flag = zombieCarService.zombieToBlack(id);
            if (flag) {
                result.success("设置成功！");
            } else {
                result.error500("设置黑名单失败,请检查该车辆是否已经是黑/白名单");
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            result.error500("设置黑名单失败,请检查该车辆是否已经是黑/白名单");
        }
        return result;
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "场内滞留车信息-通过id查询")
    @ApiOperation(value = "场内滞留车信息-通过id查询", notes = "场内滞留车信息-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<ZombieCar> queryById(@RequestParam(name = "id", required = true) String id) {
        Result<ZombieCar> result = new Result<ZombieCar>();
        ZombieCar ZombieCar = zombieCarService.getById(id);
        if (ZombieCar == null) {
            result.error500("未找到对应实体");
        } else {
            result.setResult(ZombieCar);
            result.setSuccess(true);
        }
        return result;
    }

    /**
     * 导出excel
     *
     * @param request
     * @param response
     * @Author liushengnan（修改：加入翻译）
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, HttpServletResponse response, ZombieCar ZombieCar) {

        QueryWrapper<ZombieCar> queryWrapper = QueryGenerator.initQueryWrapper(ZombieCar, request.getParameterMap());
        queryWrapper.eq("is_out", "0");
        List<ZombieCar> pageList = zombieCarService.list(queryWrapper);
        ModelAndView mv = null;
        if (pageList.size() != 0) {
            mv = new ModelAndView(new EasypoiSingleExcelView());
            for (ZombieCar ZombieCar1 : pageList) {
                if ("0".equals(ZombieCar1.getCarNature())) {
                    ZombieCar1.setCarNature("临时车");
                } else if ("1".equals(ZombieCar1.getCarNature())) {
                    ZombieCar1.setCarNature("月租车");
                } else if ("2".equals(ZombieCar1.getCarNature())) {
                    ZombieCar1.setCarNature("军警医车");
                }
                if ("0".equals(ZombieCar1.getCarType())) {
                    ZombieCar1.setCarType("无牌车");
                } else if ("1".equals(ZombieCar1.getCarType())) {
                    ZombieCar1.setCarType("有牌车");
                }
                if ("0".equals(ZombieCar1.getIsOut())) {
                    ZombieCar1.setIsOut("未出场");
                } else {
                    ZombieCar1.setIsOut("已出场");
                }
            }
            mv.addObject(NormalExcelConstants.FILE_NAME, "场内滞留车信息列表");
            mv.addObject(NormalExcelConstants.CLASS, ZombieCar.class);
            mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("场内滞留车信息列表数据", "场内车辆导出信息"));
            mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
        }
        return mv;
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            // 获取上传文件对象
            MultipartFile file = entity.getValue();
            ImportParams params = ImportParams.builder().build();
            params.setTitleRows(2);
            params.setHeadRows(1);
            params.setNeedSave(true);
            try {
                List<ZombieCar> listparkCars = ExcelImportUtil.importExcel(file.getInputStream(), ZombieCar.class, params);
                zombieCarService.saveBatch(listparkCars);
                return Result.ok("文件导入成功！数据行数:" + listparkCars.size());
            } catch (Exception e) {
                log.error(e.getMessage(), e);
                return Result.error("文件导入失败:" + e.getMessage());
            } finally {
                try {
                    file.getInputStream().close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return Result.ok("文件导入失败！");
    }
}
